package com.submit.demo.controller;

import com.submit.demo.annotation.AuthIgnore;
import com.submit.demo.common.api.CommonResult;
import com.submit.demo.service.UserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
@RequestMapping(value = "/login")
public class LoginController {
    @Autowired
    private UserService userService;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 检查登录
     */
    @ApiOperation(value = "登录以后返回token")
    @ResponseBody
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    public CommonResult checkLogin(String username, String password){
        Map<String, String> map = userService.login(username, password);
        if(map.get("token") == null){
            return CommonResult.validateFailed("用户名或密码验证码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.putAll(map);
        tokenMap.put("tokenHead", tokenHead);
        return CommonResult.success(tokenMap);
    }

    @AuthIgnore
    @ApiOperation(value = "登出功能")
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }

}
